package cn.tedu.person.config;

import cn.tedu.person.filter.JwtAuthorizationFilter;
import cn.tedu.person.web.JsonResult;
import cn.tedu.person.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //配置类上开启“基于方法的权限检查”
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    //配置jwt过滤器
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    //配置密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
        //return NoOpPasswordEncoder.getInstance();
    }

    //配置认证管理器
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(
                new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        response.setContentType("application/json; charset=utf-8");
                        String message = "未检测到登录信息，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了有效的JWT数据）";
                        log.warn(message);
                        JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
                        String jsonResultString = JSON.toJSONString(jsonResult);
                        PrintWriter writer = response.getWriter();
                        writer.println(jsonResultString);
                        writer.close();
                    }
                }
        );


        String[] urls={
            "/doc.html",
            "/**/*.css",
            "/**/*.js",
            "/swagger-resources",
            "/v2/api-docs",
            "/admin/login"
        };

        // 此方法会配置Spring Security框架自带的CorsFilter，此过滤器会对OPTIONS请求放行
        http.cors();

        http.csrf().disable();

        log.debug("开始验证登录");
        http.authorizeRequests()
                .mvcMatchers(urls)
                .permitAll()
                .anyRequest()
                .authenticated();

        //将自定义的jwt过滤器加在Spring security的
        // UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);

        //将Session策略设置为“从不使用” stateless=无状态 即从不使用Session，NEVER=从不主动创建Session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }
}
